package com.yonyou.brigade.basic_init.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.service.IMongoService;
import com.yonyou.ybzboot.starter.mongodb.dao.IMongoDao;
import com.yonyou.ybzboot.starter.mongodb.model.CriteriaMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class MongoServiceImpl implements IMongoService {

    @Autowired
    private IMongoDao mongoDao;

    private final String APPLY_INFO_RESULT = "apply_info_result";

    private final String APPLYINFORESULT = "applyInfoResult";

    @Override
    public void saveApplyResultToMongo(String tenant, String channel, JSONObject applyOrderJson, JSONObject result) {
        CriteriaMap criteriaMap = new CriteriaMap();
        criteriaMap.put("tenantId", tenant);
        criteriaMap.put("key", APPLYINFORESULT);
        criteriaMap.put("billNum", applyOrderJson.getString("billNum"));
        List<HashMap> mapList = mongoDao.findByMap(criteriaMap, HashMap.class, APPLY_INFO_RESULT);
        if (!CollectionUtils.isEmpty(mapList)) {
            mongoDao.deleteByMap(criteriaMap, APPLY_INFO_RESULT);
        }
        result.put("key", APPLYINFORESULT);
        result.put("billNum", applyOrderJson.getString("billNum"));
        result.put("tenantId", tenant);
        result.put("channel", channel);
        result.put("pushTime", new Date());
        mongoDao.getMongoTemplate().save(result, APPLY_INFO_RESULT);
    }
}
